<?php

namespace Modules\Car\Http\Controllers\Api;

use App\Helpers\Constant;
use App\Helpers\NewBaseData;
use App\Helpers\PayTrait;
use App\Helpers\ResponseData;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Modules\Car\Entities\CarOrder;
use Modules\Car\Entities\Expenses;
use Modules\Car\Entities\RecognizeDrivingLicense;
use Modules\Car\Http\Requests\Order\OrderRequest;
use Modules\Manager\Entities\Department;
use Carbon\Carbon;

//取车统计中
class PickStatisticsController extends Controller
{
    use ResponseData,NewBaseData,PayTrait;
    protected function statisticsModel(){
        return CarOrder::query()
            ->where('status',Constant::ORDER_CLOSED)
            ->where('process_status',Constant::STATISTICS_SAVE);
    }
    public function list(Request $request){
        $data = $this->statisticsModel()
            ->with('user','customer')
            ->get();
        return $this->success($data);
    }
    public function edit(OrderRequest $request){
        $data = $this->statisticsModel()
            ->where('order_sn',$request->order_sn)
            ->first();
        return $this->success($data);
    }
    protected function insertExpres($request){
        $data ['refund_deposit'] = $request->refund_deposit??0.00;
        $data ['order_sn'] = $request->order_sn;
        $data ['refund_lease_price'] = $request->refund_lease_price??0.00;
        $data ['refund_break_rules'] = $request->refund_break_rules??0.00;
        $data ['all_total'] = $request->refund_break_rules??0.00;//合计
        $data ['make_up_payment'] = $request->refund_break_rules??0.00;//补缴
        // $data ['violation_amount'] = $request->refund_break_rules??0.00;//违章金额---2024-08-17  17:17:34，这个字段现在改为实收违章押金了，这里不做更新
        Expenses::query()->insert($data);
    }
    //选择清理人
    public function chooseCleaner(OrderRequest $request){
        $order = CarOrder::query()
            ->where('order_sn',$request->order_sn)
            ->first();
        if($order){
            $order->clieaner = $request->input('clieaner',null);
            $order->save();
        }
        return $this->success('保存成功');
    }
    //统计更新
    public function update(OrderRequest $request){
        $user = $request->user();
        $order = CarOrder::query()
            ->where('order_sn',$request->order_sn)
            ->first();
        if($order){
                $this->insertExpres($request);
                //更新里程数
                $order = $this->updateData($request,$order);
                $order->fact_return_over_at = now();
                $order->refund_deposit = $request->refund_deposit??0.00;
                $order->refund_lease_price = $request->refund_lease_price??0.00;
                $order->refund_break_rules = $request->refund_break_rules??0.00;
                $order->all_total = $request->all_total??0.00;//合计
                $order->make_up_payment = $request->make_up_payment??0.00;//补缴
                // $order->violation_amount = $request->violation_amount??0.00;//违章金额---2024-08-17  17:17:34，这个字段现在改为实收违章押金了，这里不做更新


                $order->fact_send_at = $request->fact_send_at??null;//实际送车时间
                $order->dispatch_at = $request->dispatch_at??null;//实际取车(还车)时间
                $order->send_over_time = $this->isWorkOvertime($request->fact_send_at);//送车是否加班
                $order->overtime = $this->isWorkOvertime($request->dispatch_at);//还车是否加班
                $order->attribution_channel = $request->attribution_channel??'';//归属渠
                $order->manager_receivable_price = $request->manager_receivable_price??0.00;//店长设置应收
                $order->manager_handel_price = $request->manager_handel_price??0.00;//店长设置应付
                if($request->filled('refund_deposit_at')){
                    $order->refund_deposit_at = $request->refund_deposit_at;
                }
                if($request->filled('get_true_deport')){
                    $order->get_true_deport = $request->get_true_deport;
                }
                if($request->filled('clieaner')){
                    $order->clieaner = $request->clieaner;
                }
                if($request->filled('order_operator')){
                    $order->order_operator = $request->order_operator;
                }
                if($request->filled('return_employer_nickname')){
                    $order->return_employer_nickname = $request->return_employer_nickname;
                }
                if($request->filled('clieaner')){
                    $order->clieaner = $request->clieaner;
                }
                if($request->filled('reminder')){
                    $order->reminder = $request->reminder;
                }

            if($request->filled('deposit_information')){
                $order->deposit_information = $request->deposit_information;
            }
            if($request->filled('refund_information')){
                $order->refund_information = $request->refund_information;
            }
            if($request->filled('accident_maintenance')){
                $order->accident_maintenance = $request->accident_maintenance;
            }
            if($request->filled('violation_fee_information')){
                $order->violation_fee_information = $request->violation_fee_information;
            }
            if($request->filled('maintenance_cost_information')){
                $order->maintenance_cost_information = $request->maintenance_cost_information;
            }
            //违章未结清
            if($request->filled('violation_unsettle')){
                $order->violation_unsettle = $request->violation_unsettle;
            }
            //押金未结清
            if($request->filled('deposit_unsettle ')){
                $order->deposit_unsettle  = $request->deposit_unsettle ;
            }
                if($order->process_status!=6){
                    $order->process_status = Constant::STATISTICS_SAVE;
                }

                $order->all_handel_amount = $request->input('all_handel_amount',0.00);
                $order->save();

                return $this->success('更新成功');
     }else{
            return $this->failed('订单不存在',201);
        }
    }
    //更新里程数
    protected function updateData($request,$order){
        $car = RecognizeDrivingLicense::query()->find($order->gear_car_id);
        if(!$car){
            // return $this->failed('车辆不存在',201);
            return $order;
        }
        if($request->filled('get_mileage')){
            $order->get_mileage = $request->get_mileage;
            $last_mileage = $order->send_mileage-$request->get_mileage;
            $car->total_mileage = $request->get_mileage;
            $car->spark_plug_mileage = $last_mileage;
            $car->gearbox_mileage = $last_mileage;
            if($request->filled('spark_plug_mileage')){//火花塞公里数
                $car->spark_plug_mileage = $request->spark_plug_mileage;
            }
            if($request->filled('gearbox_mileage')){//变速箱公里数
                $car->gearbox_mileage = $request->gearbox_mileage;
            }
        }else{
            if($request->filled('spark_plug_mileage')){//火花塞公里数
                $car->spark_plug_mileage = $request->spark_plug_mileage;
            }
            if($request->filled('gearbox_mileage')){//变速箱公里数
                $car->gearbox_mileage = $request->gearbox_mileage;
            }
        }

        $car->save();

        return $order;
    }
    //确认成功
    public function finish(OrderRequest $request){
        $user = $request->user();
        $order = CarOrder::query()
            ->where('order_sn',$request->order_sn)
            ->first();
        if($order&&$order->order_part_refund==0){
            //更新里程数
            $order = $this->updateData($request,$order);
            $order->refund_deposit = $request->refund_deposit??0.00;
            $order->refund_lease_price = $request->refund_lease_price??0.00;
            $order->refund_break_rules = $request->refund_break_rules??0.00;
            $order->all_total = $request->all_total??0.00;//合计
            $order->make_up_payment = $request->make_up_payment??0.00;//补缴
            // $order->violation_amount = $request->violation_amount??0.00;//违章金额---2024-08-17  17:17:34，这个字段现在改为实收违章押金了，这里不做更新
            $order->order_part_refund = 1;
            $order->process_status = Constant::HISTORY_ORDER;


            $order->fact_send_at = $request->fact_send_at??null;//实际送车时间
            $order->dispatch_at = $request->dispatch_at??null;//实际取车(还车)时间
            $order->send_over_time = $this->isWorkOvertime($request->fact_send_at);//送车是否加班
            $order->overtime = $this->isWorkOvertime($request->dispatch_at);//还车是否加班
            $order->attribution_channel = $request->attribution_channel??'';//归属渠道
            $order->manager_receivable_price = $request->manager_receivable_price??0.00;//店长设置应收
            $order->manager_handel_price = $request->manager_handel_price??0.00;//店长设置应付
            if($request->filled('confirm_change_price')){
                $order->confirm_change_price = 1;
            }
            if($request->filled('manager_receivable_price')){
                $order->bc_total = $request->manager_receivable_price;
            }
            if($request->filled('refund_deposit_at')){
                $order->refund_deposit_at = $request->refund_deposit_at;
            }
            if($request->filled('get_true_deport')){
                $order->get_true_deport = $request->get_true_deport;
            }
            if($request->filled('clieaner')){
                $order->clieaner = $request->clieaner;
            }
            if($request->filled('order_operator')){
                $order->order_operator = $request->order_operator;
            }
            if($request->filled('return_employer_nickname')){
                $order->return_employer_nickname = $request->return_employer_nickname;
            }
            if($request->filled('clieaner')){
                $order->clieaner = $request->clieaner;
            }
            if($request->filled('deposit_information')){
                $order->deposit_information = $request->deposit_information;
            }
            if($request->filled('refund_information')){
                $order->refund_information = $request->refund_information;
            }
            if($request->filled('accident_maintenance')){
                $order->accident_maintenance = $request->accident_maintenance;
            }
            if($request->filled('violation_fee_information')){
                $order->violation_fee_information = $request->violation_fee_information;
            }
            if($request->filled('maintenance_cost_information')){
                $order->maintenance_cost_information = $request->maintenance_cost_information;
            }

            if($request->filled('true_get_online_lease_price')){
                $order->true_get_online_lease_price = $request->true_get_online_lease_price;
            }
            if($request->filled('true_get_off_lease_price')){
                $order->true_get_off_lease_price = $request->true_get_off_lease_price;
            }
            if($request->filled('unpaid')){
                $order->unpaid = $request->unpaid;
            }
            //违章未结清
            if($request->filled('violation_unsettle')){
                $order->violation_unsettle = $request->violation_unsettle;
            }
            //押金未结清
            if($request->filled('deposit_unsettle ')){
                $order->deposit_unsettle  = $request->deposit_unsettle ;
            }
            if($request->filled('settle_status')){
                $order->settle_status = $request->settle_status;
            }
            if($request->filled('mini_refund_pay')){
                $order->mini_refund_pay = $request->mini_refund_pay;
                if($request->mini_refund_pay>0){
                    $money = $request->mini_refund_pay*100;
                    DB::update('update car_orders set order_part_refund_total=order_part_refund_total+?,order_part_refund = ?, order_part_refund_at = ?,order_part_refund_id = ?,order_part_refund_nick_name = ?  WHERE order_part_refund = ? and order_sn = ?',
                        [$request->mini_refund_pay,1,now(),$user->id,$user->nick_name,0,$order->order_sn]);

                    $this->miniRefund($order->order_sn,$order->out_trade_no,$money,$order->mini_pay);
                }
            }
            $order->save();
            return $this->success($order);
        }else{
            return $this->failed('订单不存在',201);
        }
    }
    //    是否加班
    public function isWorkOvertime($time){
        if($time){
            $acc = strtotime($time);
            $now_num = date('Hi',$acc);
            if($now_num>1800||$now_num<730){
                return 1;
            }else{
                return 0;
            }
        }
       return 0;
    }
    //未结清订单
    public function isNotSettle(Request $request){
        $user = $request->user();
        $size = $request->input('size',10);
        $model = $this->searchOrderModel($request);
        if($request->filled('uncleared_status')){
            // if($request->uncleared_status==1){//违章
            //     $model  = $model->where('violation_unsettle','<>',0);
            // }elseif($request->deposit_unsettle==1){//押金
            //     $model  = $model->where('deposit_unsettle','<>',0);
            // }elseif($request->deposit_unsettle==2){//费用
            //     $model  = $model->where('unpaid','<>',0);
            // }
            if($request->uncleared_status==3){
                $model  = $model->whereIn('uncleared_status',[0,3]);
            } else {
                $model  = $model->where('uncleared_status',$request->uncleared_status);
            }
        }
        if($request->filled('settle_status')){
            $model  = $model->where('settle_status',$request->settle_status);
        }
        if($request->filled('now_month')){
            $startOfMonth = Carbon::now()->startOfMonth();
            $endOfMonth = Carbon::now()->endOfMonth();
            $model  = $model->whereBetween('updated_at', [$startOfMonth, $endOfMonth]);
        }
        // 待结算列表排序，最新的订单排最后，历史待结算的订单排第一；未结清列表排序，一样。
        if($user->post_id==2){
            $data = $model
                ->where('status',6)
//                ->where('is_closed',1)
                ->whereIn('process_status',[4,5])
                ->where('department',$user->department_id)
                // ->orderByDesc('id')
                ->orderBy('id', 'asc')

                ->paginate($size);
        }else{
            if($request->filled('department')&&$request->department){
                $model = $model->where('department',$request->department);
            }
            $data = $model
                ->where('status',6)
//                ->where('is_closed',1)
                ->whereIn('process_status',[4,5])
                // ->orderByDesc('return_time')
                ->orderBy('id', 'asc')
                ->paginate($size);
        }

        return $this->success($data);
    }
    //修改订单改价状态
    public function changePriceConfirm(CarOrder $model,Request $request){

        $user = $request->user();

        $department = $user->department_id;
        // 当前部门基础信息
        $hasId = [];
        $departmentlist = Department::query()->get();
        foreach($departmentlist as $item){
            $change_price_notify = $item->change_price_notify;
            if(in_array($department, $change_price_notify)){
                $hasId[] = $item->id;
            }
        }
//        $model= $model->with('user','gear','customer','car',"customer");
        $model = $this->searchOrderModel($request);
       if($user->post_id==2){
            // 店长根据配置，查自己能看的数据
            if (count($hasId) > 0) {
                $model = $model->where('confirm_change_price',1)->whereIn('department',$hasId);
            } else {
                $model = $model->where('confirm_change_price',-99);
            }
       } else {
            // 管理可以看全部
            $model = $model->where('confirm_change_price',1);
       }
        // switch ($department){
        //     case 1://总店
        //         if($user->post_id==2){
        //             $model = $model->where('confirm_change_price',1);
        //         }else{
        //             $model = $model->where('department',6)->where('confirm_change_price',1);
        //         }

        //         break;
        //     case 2://途安店
        //         $model =$model
        //             ->whereIn('department',[3,4])
        //             ->where('confirm_change_price',1);
        //         break;
        //     case 3://贝村店
        //         $model =$model
        //             ->where('department',2)
        //             ->where('confirm_change_price',1);
        //         break;
        //     case 4://柳青店
        //         $model =$model
        //             ->where('department',10)
        //             ->where('confirm_change_price',1);
        //         break;
        //     default:
        //         $model = $model
        //             ->where('department',10)
        //             ->where('confirm_change_price',1);
        //         break;
        // }
        $model = $model->orderByDesc('id');
        $size = $request->input('size',10);
        $order = $model->paginate($size);
        if(!$order){
            return $this->failed('订单不存在',201);
        }
        return $this->success($order);
    }

}
